/*
 * Copyright 2007 Mojo Chen
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

var linkxd = {
	
    //fireBeforeImagesLoaded: false,
    //topLevelDocumentsOnly: true,
    
	keyMode : 'HTML',
	
  	onLoad: function() {
  		
  		this.consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
        this.promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  		
  		dump('Load overlay.js');
    	// initialization code
    	this.initialized = true;
    	this.strings = document.getElementById("linkxd-strings");
    	document.getElementById("contentAreaContextMenu")
            .addEventListener("popupshowing", function(e) { linkxd.showContextMenu(e); }, false);			
		
		linkxdDb.init();
		
		// content load
		//if(this.fireBeforeImagesLoaded) this.loadType = "DOMContentLoaded";
        //else this.loadType = "load";
        //gBrowser.addEventListener(this.loadType,function(event) { linkxd.onContentLoaded(event); },true);
  	},
  	
    onContentLoaded: function(event) {
        
        var doc = event.originalTarget;
        

        var message = 'type='+this.loadType + ',title=' + doc.title + ', URI=' + doc.documentURI;
        linkxdMain.log("linkxd onContentLoaded :"  + message);

        // Only for top level documents and not subframes?
        if(this.topLevelDocumentsOnly) {
            // When this becomes true it means that
            // all of the top level document's
            // subframes have also finished loading
            if(!this.isTopLevelDocument(doc)) {
            	//linkxd.log('not top level document.');
        		linkxdMain.log("onContentLoaded(): this doc is not top level document!");
            	return;
            }
        }
        

        // Get the browser for the document (if required)
        var browser = this.getBrowserForDocument(doc);
        if(!browser) return;

        // If you have enabled topLevelDocuments only and
        // want to get all documents contained in the browser
        // for processing, do it like so
        var documents = this.getDocuments(browser.contentWindow,new Array());
    }, 
  	
  	
  	isTopLevelDocument: function(aDocument) {
  		
  		// http://developer.mozilla.org/en/docs/Code_snippets:Tabbed_browser
        var browsers = gBrowser.browsers;
        // Log/alert
        //linkxd.log('browsers.length:' + browsers.length);
        
        var result = false;
        for(var i = 0; i < browsers.length; i++) {
        	var b = browsers[i];
        	//linkxd.log('b.currentURI.spec:'+b.currentURI.spec);
            if(aDocument == browsers[i].contentDocument){
            	 result = true;
            	 break;
            }
        }
        
        // title is not null and result is false ... check for funp
        var msg = 'isTopLevelDocument(),title:' + aDocument.title;
        msg += ', location:' + aDocument.location;
        msg += ', URL:' + aDocument.URL;
        msg += ' isTopLevelDocument:'+ result;
        
        linkxd.log(msg);
        
        if(aDocument.title && !result){
        	linkxd.log('===>iframe in funp. title is true and isTopLevelDocument is false');
        }
        return result;
    },

    getDocuments: function(aFrame,aArray) {
        var frames = aFrame.frames;
        aArray.push(aFrame.document);
        for(var i = 0; i < frames.length; i++) this.getDocuments(frames[i],aArray);
        return aArray;
    },

    getBrowserForDocument: function(aDocument) {
        // This function can return the browser for not only top level documents
        // but also documents contained in subframes

        // If the document is top level then return its browser here
        var browsers = gBrowser.browsers;
        for(var i = 0; i < browsers.length; i++) {
            if(aDocument == browsers[i].contentDocument) return browsers[i];
        }

        // Else it must be in a subframe, so check all frames in each browser
        // to find the parent browser
        var documents;
        for(var j = 0; j < browsers.length; j++) {
            documents = this.getDocuments(browsers[j].contentWindow,new Array());
            for(var k = 0; k < documents.length; k++) {
                if(aDocument == documents[k]) return browsers[j];
            }
        }

        // Else the browser could not be determined
        return null;
    },

  	showContextMenu: function(event) {
    	document.getElementById("context-linkxd").hidden = gContextMenu.onImage;
  	},
  	
  	onGold:function(){
  		try{
  			linkxdGold.invokeMyGold(function(){
				var text = linkxdGold.getPasteHtml();
				linkxdMain.log('info', text);
				linkxdMain.paste(text);
				alert('OK!');
			});
  		}catch(err){
			linkxdMain.log('Error', err);
		}
  	},
  	
  	onKeyHotLink:function(e){
  		//
  		// alert(result);
  		//window.open("chrome://linkxd/content/chooseLink.xul", "bmarks", "chrome,centerscreen,dialog,top=100");
  		//window.open("chrome://linkxd/content/foo/foo.xul", "bmarks", "chrome,centerscreen");
  		// TEST foo.xhtml
  		//window.open("chrome://linkxd/content/foo.xhtml", "bmarks", "chrome,centerscreen,dialog,top=100");
  		// TEST yui-editor1.html
  		//window.open("chrome://linkxd/content/foo/yui-editor1.html", "YUIEditor", "chrome,resizable=yes,scrollbars=yes,status=yes");
  		// Not work
  		//window.open("chrome://linkxd/content/yui-editor2.xul", "YUIEditor", "chrome,centerscreen");
  		// Not Work
  		//window.open("chrome://linkxd/content/yui-editor2.html", "YUIEditor", "chrome,centerscreen");
  		// OK .... chrome link problem...
  		//window.open("http://developer.yahoo.com/yui/examples/editor/cal_editor.html", "YUIEditor", "centerscreen");
  		// OK
  		//window.open("file:///C:/xx/extensions/linkxd@mojox/content/yui-editor2.html", "YUIEditor", "centerscreen");
  		// get profile directory
  		// AChrm %installation%/chrome
  		// UChrm %profile%/chrome
  		// ProfD 	 profile directory
  		
  		var id = "linkxd@mojox";
  		var extension = Components.classes["@mozilla.org/extensions/manager;1"].getService(Components.interfaces.nsIExtensionManager).getInstallLocation(id).getItemLocation(id);
  		// extension is nsIFile
  		var ios = Components.classes["@mozilla.org/network/io-service;1"]
                    .getService(Components.interfaces.nsIIOService);
		var fileHandler = ios.getProtocolHandler("file")
                     .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
        
        var exURL = fileHandler.getURLSpecFromFile(extension);
        
        // TODO How to know chrome dir ??
        // local test with /content/yui-editor2.html
        // xpi test with /chrome/content/yui-editor2.html
        
  		var result = 'chrome/content/';
        extension.append("chrome");
        //alert(extension.path); // now is extension/id/chrome
        if( !extension.exists() || !extension.isDirectory() ) {   
        	// if it doesn't exist, create
        	result = 'content/';
        }
        
  		//alert(exURL+result+'yui-editor2.html');
  		// default 800x600
  		window.open(exURL+result+'foo/yui-editor3.html', "YUIEditor", "centerscreen,width=800,height=600");
  	},
  
  	onLinkxdPush: function(e) {
  		var plink = '<a href="http://linkxd.com"><img style="border:0;vertical-align:middle;" alt="LinkXD" title="' +
  			linkxdMain.getString("push.title") +
  			'" src="http://linkxd.com/images/linkxd.png"/></a>';
  		linkxdMain.paste(plink);
  	},
  
  	onLink: function(e,handler) {
     	var str = this.getSelectStr();
	  	var url = this.getLocationUrl();
	  	if(str != null && str.length > 0){
		  	this.processStr(str);
		  	linkxdMain.paste(handler.getLink(url,str));
	  	}else{
		  	linkxdMain.paste(handler.getLink(url,content.document.title));
	  	}
  	},
  
  	onTest: function(){
  		linkxdGold.onTest();
  	},
  
  onQuote: function(e,handler) {
 
   var str = this.getSelectStr();
	var url = this.getLocationUrl();
	this.processStr(str);
	linkxdMain.paste(handler.getQuote(url,content.document.title,str));
  },
  
  onWikiLink: function(e) {
	this.onLink(e,linkxdWiki);
  },
  
  setKeyMode: function(mode) {
  	alert('Change to mode : ' + mode);
  	this.keyMode = mode;
  },
  
  onKeyLink: function(e) {
  	 switch(this.keyMode){
			case 'HTML':
				this.onHtmlLink(e);
				break;
			case 'WIKI': 
				this.onWikiLink(e);
				break;
			case 'BB':
				this.onBBLink(e);
				break;
	}	
  },
  
  onKeyQuote: function(e) {
  	 switch(this.keyMode){
			case 'HTML':
				this.onHtmlQuote(e);
				break;
			case 'WIKI': 
				this.onWikiQuote(e);
				break;
			case 'BB':
				this.onBBQuote(e);
				break;
	}	
  },
  
  	onWikiQuote: function(e) {
   		this.onQuote(e,linkxdWiki);
  	},
  
  	onHtmlLink: function(e) {
    	this.onLink(e,linkxdHtml);
  	},
  
  	onHtmlQuote: function(e) {
		this.onQuote(e,linkxdHtml);
  	},
  
  	onBBLink: function(e) {
     	this.onLink(e,linkxdBB);
  	},
  
  	onBBQuote: function(e) {
   		this.onQuote(e,linkxdBB);
  	},
  
  	onBkFunp: function(e) {
   		var summary = this.getSelectStr();
   		this.processStr(summary);
   		var url = this.getLocationUrl();
		var title = content.document.title;
		linkxdBK.putFunp(title,url,summary);
  	},
  
  	onBkHemi: function(e) {
   		var summary = this.getSelectStr();
   		this.processStr(summary);
   		var url = this.getLocationUrl();
		var title = content.document.title;
		linkxdBK.putHemi(title,url,summary);
  	},
  
  	onDbLink: function(e,tagId) {
   		var summary = this.getSelectStr();
   		var url = this.getLocationUrl();
		var title = content.document.title;
		if(summary != null && summary.length > 0){
			this.processStr(summary);
			title = summary;
			summary = null;
		}
		//linkxdDb.insertLink(title,url,summary,type);
		linkxdDb.insertTagLink(title,url,summary,tagId);
  	},
  
  	onDbQuote: function(e,tagId) {
		var summary = this.getSelectStr();
   		var url = this.getLocationUrl();
		var title = content.document.title;
		this.processStr(summary);
		//linkxdDb.insertLink(title,url,summary,type);
		linkxdDb.insertTagLink(title,url,summary,tagId);
  	},
  
  	onAlert: function(msg) {
    	var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                                  .getService(Components.interfaces.nsIPromptService);
    	promptService.alert(window,'Alert',msg);
  	},
  
  	onTodo: function(e) {
    	this.Alert('TODO');
  	},
  	
	getSelectStr: function(){
		var fwin = document.commandDispatcher.focusedWindow;
    	var sel = fwin.getSelection();    	
    	// TEST in ContextMenu
    	//this.testImgSelect();
    	//  var isContentSelected = !fwin.getSelection().isCollapsed;
		return sel.toString();
  	},
  	
  	isContentSelected : function(){
		var fwin = document.commandDispatcher.focusedWindow;
  		return !fwin.getSelection().isCollapsed;
  	},
	
	getLocationUrl: function(){
		var fwin = document.commandDispatcher.focusedWindow;
		var url = fwin.location.href;
		url = url.replace(/&/g, "&amp;");
		return url;
	},
	
	processStr: function(str){
		if(str != null && str.length > 0){
			// Trim, remove newlines, compact duplicate spaces
			str = str.replace(/^\s*|\s*$/g, "");
			str = str.replace(/[\n\r]/g, " ");
			str = str.replace(/\s+/g, " ");
        
    		// escape characters with special html meaning
    		str = str.replace(/&/g, "&amp;");
    		str = str.replace(/</g, "&lt;");
    		str = str.replace(/>/g, "&gt;");
		}
  	}
};
window.addEventListener("load", function(e) { linkxd.onLoad(e); }, false);
